<?php

namespace addons\shopro\controller\commission;

use think\Db;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\commission\Agent as AgentModel;
use app\admin\model\shopro\goods\Goods as GoodsModel;
use addons\shopro\service\Wallet;


class Agent extends Commission
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    // 分销商详情
    public function index()
    {
        $status = $this->service->getAgentStatus(true);

        $condition = [
            'type' => '',
            'value' => ''
        ];

        switch ($status) {
            case AgentModel::AGENT_STATUS_NULL:
                $condition = $this->service->config->getBecomeAgentEvent();
                if ($condition['type'] === 'goods') {
                    $condition['value'] = GoodsModel::show()->whereIn('id', $condition['value'])->select();
                }
                $this->error('', $condition, 100);
                break;
            case AgentModel::AGENT_STATUS_NEEDINFO:
                $this->error('待完善信息,请补充您的资料后提交审核', $condition, 103);
                break;
            case AgentModel::AGENT_STATUS_PENDING:
                $this->error('正在审核中,请耐心等候结果', $condition, 104);
                break;
            case AgentModel::AGENT_STATUS_REJECT:
                $agentFormStatus = $this->service->config->isAgentApplyForm();
                if ($agentFormStatus) {
                    $this->error('抱歉!您的申请信息未通过,请尝试修改后重新提交', $condition, 105);
                } else {
                    $this->error('抱歉!您的申请未通过,请尝试重新申请', $condition, 106);
                }
                break;
            case AgentModel::AGENT_STATUS_FREEZE:
                $this->error('抱歉!您的账户已被冻结,如有疑问请联系客服', $condition, 107);
                break;
        }
        $data = $this->service->agent;

        $this->success('分销商信息', $data);
    }

    // 分销商完善个人信息
    public function form()
    {
        if (!$this->service->config->isAgentApplyForm()) {
            $this->error('未开启分销商申请');
        }

        $agentForm = $this->service->config->getAgentForm();
        $protocol = $this->service->config->getApplyProtocol();
        $applyInfo = $this->service->agent->apply_info ?? [];

        $config = [
            'form' => $agentForm['content'],
            'status' => $this->service->getAgentStatus(true),
            'background' => $agentForm['background_image'],
            'protocol' => $protocol,
            'applyInfo' => $applyInfo
        ];

        $this->success("", $config);
    }


    // 申请分销商/完善资料
    public function apply()
    {
        if (!$this->service->config->isAgentApplyForm()) {
            $this->error('未开启分销商申请');
        }
        $status = $this->service->getAgentStatus(true);

        if (!in_array($status, [AgentModel::AGENT_STATUS_NEEDINFO, AgentModel::AGENT_STATUS_REJECT, AgentModel::AGENT_STATUS_NORMAL])) {
            $this->error('您暂时不能申请');
        }
        Db::transaction(function () use ($status) {
            $data = $this->request->param('data/a');
            // 过滤无效表单字段数据
            $config = $this->service->config->getAgentForm();
            $form = (array)$config['content'];
            $data = array_column($data, 'value', 'name');
            foreach ($form as &$item) {
                if (!empty($data[$item['name']])) {
                    $item['value'] = $data[$item['name']];
                } else {
                    $this->error($item['name'] . '不能为空');
                }
            }
            if ($status === AgentModel::AGENT_STATUS_NEEDINFO) {
                $this->service->createNewAgent('', $form);
            } else {
                // 重置为审核中
                if ($status === AgentModel::AGENT_STATUS_REJECT) {
                    $this->service->agent->status = AgentModel::AGENT_STATUS_PENDING;
                }
                // 更新分销商信息
                $this->service->agent->apply_info = $form;
                $this->service->agent->save();
            }
        });

        $this->success('提交成功');
    }

    // 我的团队
    public function team()
    {
        $agentId = $this->service->user->id;
        $data = UserModel::where('parent_user_id', $agentId)
            ->where('status', 'normal')
            ->with(['agent' => function ($query) {
                return $query->with('level_info');
            }])
            ->paginate($this->request->param('list_rows', 8));

        $this->success("", $data);
    }
    //获取下级详情列表
    public function getChildList(){
        $agentId = $this->service->user->id;
        $type=$this->request->param("type","tourist");//tourist=游客 vip=鸡蛋会员
        $pid=$this->request->param("pid",-1);//上级id
        /*if(!in_array($agentId,$this->getTopPid($pid))){
            $this->error("对不起！您没有该用户的下级查看权限");
        }*/
        $userModel=new UserModel();
        $where=["parent_user_id"=>$pid];
        if($type=="vip"){
            $where["egg_vip"]=1;
            $where["egg_vip_end_time"]=[">=",date("Y-m-d H:i:s")];
        }
        $userData=$userModel->where($where)->field("id,avatar,nickname,createtime")->paginate($this->request->param("list_rows",10));
        $this->success("获取成功",$userData);
    }
    //获取最上级的id
    private function getTopPid($userId){
        $idsArr=[];
        $userModel=new UserModel();
        $userData=$userModel->where(["id"=>$userId])->field("id,parent_user_id")->find();
        if($userData && $userData["parent_user_id"] != "0"){
            $idsArr[]=$userData["id"];
            $idsArr=array_merge($idsArr,$this->getTopPid($userData["parent_user_id"]));
        }
        return $idsArr;
    }
    //获取游客和会员一级二级列表
    public function teamlist(){
        $agentId = $this->service->user->id;
        $type=$this->request->param("type","tourist");//tourist=游客 vip=鸡蛋会员
        $level=$this->request->param("level","1");
        $cacheString=redis_cache("agent_child_data_id_".$agentId);
        if(!$cacheString){
            $res=$this->getChild($agentId);
            redis_cache("agent_child_data_id_".$agentId,json_encode($res),1800);
            $cacheString=redis_cache("agent_child_data_id_".$agentId);
        }
        $childData=json_decode($cacheString,true);
        if($type=="vip"){
            $field=$level=="1"?"vip_level_1":"vip_level_2";
        }else{
            $field=$level=="1"?"tourist_level_1":"tourist_level_2";
        }
        $userData=[];
        if($childData[$field]){
            $userModel=new UserModel();
            $where=["parent_user_id"=>["in",$childData[$field]]];
            if($type=="vip"){
                $where["egg_vip"]=1;
                $where["egg_vip_end_time"]=[">=",date("Y-m-d H:i:s")];
            }
            $userData=$userModel->where($where)->field("id,avatar,nickname,createtime")->paginate($this->request->param("list_rows",10));
            if($userData){
               foreach ($userData as &$user){
                   $user["childCount"]=$userModel->where($where)->count();
               }
            }
        }
        $this->success("获取成功",$userData);
    }
    //我的团队新
    public function myteam(){
        $agentId = $this->service->user->id;
        $lock=redis_cache('agent_child_lock_'.$agentId);
        if($lock) $this->error('请不要毛起点,谢谢！');
        redis_cache('agent_child_lock_'.$agentId,"1");
        $res=redis_cache("agent_child_data_id_".$agentId);
        if($res){
            $res=json_decode($res,true);
        }else{
            $res=$this->getChild($agentId);
            redis_cache("agent_child_data_id_".$agentId,json_encode($res),1800);
        }
        //将一级二级游客和鸡蛋会员id存入缓存
        unset($res["vip_level_1_id"]);
        unset($res["vip_level_2_id"]);
        unset($res["tourist_level_1_id"]);
        unset($res["tourist_level_2_id"]);
        redis_cache('agent_child_lock_'.$agentId,null);
        $this->success("获取成功",$res);
    }
    //获取用户的下级人数
    private function getChild($userId,$level=1){
        $data=[
            "vip_total"      =>0,//鸡蛋会员总数
            "tourist_total"  =>0,//游客总数
            "vip_level_1"    =>0,//一级鸡蛋会员
            "vip_level_2"    =>0,//二级鸡蛋会员
            "tourist_level_1"=>0,//一级游客
            "tourist_level_2"=>0,//二级游客
            "vip_level_1_id"    =>[],//一级鸡蛋会员id
            "vip_level_2_id"    =>[],//二级鸡蛋会员id
            "tourist_level_1_id"=>[],//一级游客id
            "tourist_level_2_id"=>[],//二级游客id
        ];
        $userModel=new UserModel();
        $userData=$userModel->where(["parent_user_id"=>$userId])->field("id,egg_vip,egg_vip_end_time")->select();
        if($userData){
            foreach ($userData as $k=>$v){
                if($v["egg_vip"]==1 && strtotime($v["egg_vip_end_time"])>=time()){
                    $data["vip_total"]=$data["vip_total"]+1;
                }else{
                    $data["tourist_total"]=$data["tourist_total"]+1;
                }
                if($level==1){
                    if($v["egg_vip"]==1 && strtotime($v["egg_vip_end_time"])>=time()){//鸡蛋会员
                        $data["vip_level_1"]=$data["vip_level_1"]+1;
                        $data["vip_level_1_id"][]=$v["id"];
                    }else{//游客
                        $data["tourist_level_1"]=$data["tourist_level_1"]+1;
                        $data["tourist_level_1_id"]=$v["id"];
                    }
                }
                if($level==2){
                    if($v["egg_vip"]==1 && strtotime($v["egg_vip_end_time"])>=time()){//鸡蛋会员
                        $data["vip_level_2"]=$data["vip_level_2"]+1;
                        $data["vip_level_2_id"][]=$v["id"];
                    }else{//游客
                        $data["tourist_level_2"]=$data["tourist_level_2"]+1;
                        $data["tourist_level_2_id"][]=$v["id"];
                    }
                }
                $level++;
                $newData=$this->getChild($v["id"],$level);
                $data["vip_total"]=bcadd($data["vip_total"],$newData["vip_total"]);
                $data["tourist_total"]=bcadd($data["tourist_total"],$newData["tourist_total"]);
                $data["vip_level_1"]=bcadd($data["vip_level_1"],$newData["vip_level_1"]);
                $data["vip_level_2"]=bcadd($data["vip_level_2"],$newData["vip_level_2"]);
                $data["tourist_level_1"]=bcadd($data["tourist_level_1"],$newData["tourist_level_1"]);
                $data["tourist_level_2"]=bcadd($data["tourist_level_2"],$newData["tourist_level_2"]);
                $data["vip_level_1_id"]=array_merge($data["vip_level_1_id"],$newData["vip_level_1_id"]);
                $data["vip_level_2_id"]=array_merge($data["vip_level_2_id"],$newData["vip_level_2_id"]);
                $data["tourist_level_1_id"]=array_merge($data["tourist_level_1_id"],$newData["tourist_level_1_id"]);
                $data["tourist_level_2_id"]=array_merge($data["tourist_level_2_id"],$newData["tourist_level_2_id"]);
            }
        }
        return $data;
    }

    // 佣金转余额
    public function transfer()
    {
        $amount = $this->request->param('amount');
        if ($amount <= 0) {
            $this->error('请输入正确的金额');
        }
        Db::transaction(function () use ($amount) {
            $user = auth_user();
            Wallet::change($user, 'commission', -$amount, 'transfer_to_money');
            Wallet::change($user, 'money', $amount, 'transfer_by_commission');
        });
        $this->success('');
    }
}
